package com.hktf.moedokilock.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.hktf.corelib.constant.KEYS;
import com.hktf.corelib.eventBus.ObjectEvent;
import com.hktf.corelib.utils.CommUtils;
import com.hktf.corelib.utils.MMKVUtils;
import com.hktf.corelib.utils.UIUtils;
import com.hktf.moedokilock.fragment.MainFragment0;
import com.hktf.moedokilock.fragment.MineFragment;
import com.hktf.moedokilock.R;
import com.hktf.moedokilock.bean.MainItem;

import com.hktf.corelib.utils.ButtonUtil;
import com.hktf.corelib.utils.ButtonUtils;
import com.hktf.corelib.utils.LogMds;
import com.hktf.moedokilock.adapter.MainItemAdapter;
import com.hktf.moedokilock.widget.FloatingLockscreen;
import com.hktf.uilib.app.BaseActivity;
import com.hktf.uilib.app.UiApplication;
import com.hktf.uilib.utils.DlgUtils;
import com.hktf.uilib.widget.FloatingActionButton;


import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends BaseActivity implements OnClickListener {
    private static final String TAG = "MainActivity";
    //hexunwu TODO 退出应用提示框

    private MainFragment0 mainFragment0;
    private MineFragment mineFragment;
    private FragmentManager fm;
    private RecyclerView recyclerView;

    @Override
    public int getLayoutResID() {
        return R.layout.activity_main;
    }

    @Override
    public boolean isLayoutFitsSystemWindows() {
        return true;
    }

    public boolean isStatusBarAndNavBarUiWhite() {
        return false;
    }

    @Override
    public void initView() {
        mainFragment0 = new MainFragment0();
        fm = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fm.beginTransaction();
        fragmentTransaction.replace(R.id.content_layout, mainFragment0);
        fragmentTransaction.commit();

        recyclerView = findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new GridLayoutManager(this, 2));
//        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
//        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
//        recyclerView.setLayoutManager(linearLayoutManager);
        String[] tabs = getResources().getStringArray(R.array.tab_item);
        int[] checkedResIds = new int[]{R.drawable.home_on, R.drawable.my_on};
        int[] norMalResIds = new int[]{R.drawable.home_off, R.drawable.my_off};
        List<MainItem> list = new ArrayList<>();
        for (int i = 0; i < tabs.length; i++) {
            MainItem mainItem = new MainItem();
            if (i == 0) {
                //                mainItem.setType(0);
                mainItem.setChecked(true);
            }

            mainItem.setTitle(tabs[i]);
            mainItem.setImgNormalResId(norMalResIds[i]);
            mainItem.setImgSelectedResId(checkedResIds[i]);
            list.add(mainItem);
        }
        mainItemAdapter = new MainItemAdapter(list);
        recyclerView.setAdapter(mainItemAdapter);
        mainItemAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                MainActivity.this.onItemClick(position);
            }
        });
    }



    @Override
    public void initListener() {

        // 注册广播接收器
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_USER_PRESENT);
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        filter.addAction(Intent.ACTION_SCREEN_ON);
        filter.setPriority(Integer.MAX_VALUE);
        registerReceiver(screenReceiver, filter);

    }

    private FloatingActionButton floatingActionButton;

    @Override
    public void initData() {
    }


    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }


    @Override
    protected void onStart() {
        super.onStart();

    }


//    @Override
//    public boolean onKeyDown(int keyCode, KeyEvent event) {// 主要是对这个函数的复写
//        // TODO Auto-generated method stub
//        if ((keyCode == KeyEvent.KEYCODE_BACK)
//                && (event.getAction() == KeyEvent.ACTION_DOWN)) {
////            close();
//            return true;
//        }
//        return super.onKeyDown(keyCode, event);
//    }



    public void onDestroy() {
        super.onDestroy();
        // 注销广播接收器
        try {
            unregisterReceiver(screenReceiver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
    }

    @Override
    protected void onStop() {
        // TODO Auto-generated method stub
        super.onStop();

    }

    public void close(){
        exitApp();
    }






    private MainItemAdapter mainItemAdapter;
    private int currentPosition = 0;

    public void onItemClick(final int position) {
        if(position==currentPosition){
            return;
        }
        LogMds.i("cdz", "hidden onItemCli" +
                "ck position=" + position);
        if (ButtonUtil.isFastDoubleClick(1, 2000) && position == 3) {
            LogMds.e("cdz", "hidden 双击了.....position=" + position);
            return;
        }


        // TODO: 2022/12/9 标签选中
        for (MainItem datum : mainItemAdapter.getData()) {
            datum.setChecked(false);
        }

        mainItemAdapter.getItem(position).setChecked(true);
        mainItemAdapter.notifyDataSetChanged();
        showFragment(position);
    }

    /**
     * 隐藏fragment的共有方法
     *
     * @param fragment
     * @param ft
     */
    private void hideFragment(Fragment fragment, FragmentTransaction ft) {
        if (fragment != null) {
            ft.hide(fragment);
        }
    }

    /**
     * 隐藏fragment的共有方法
     *
     * @param ft
     */
    private void hideAllFragment(FragmentTransaction ft) {
        hideFragment(mainFragment0, ft);
        hideFragment(mineFragment, ft);
//        hideFragment(mainFragment3, ft);
//        hideFragment(mainFragment1, ft);
//        hideFragment(mainFragment2, ft);
    }

    @Override
    public void onClick(View view) {
        //防止多次点击
        if (ButtonUtils.isFastDoubleClick()) {
            return;
        }


    }

    public void showFragment(int position) {
        currentPosition = position;
        FragmentTransaction fragmentTransaction = fm.beginTransaction();
        hideAllFragment(fragmentTransaction);
        switch (position) {
            case 0:
                if (mainFragment0 == null) {
                    mainFragment0 = new MainFragment0();
                    fragmentTransaction.add(R.id.content_layout, mainFragment0);
                } else {
                    fragmentTransaction.show(mainFragment0);
                }
                break;
            case 1:
                //我的
                if (mineFragment == null) {
                    mineFragment = new MineFragment();
                    fragmentTransaction.add(R.id.content_layout, mineFragment);
                } else {
                    fragmentTransaction.show(mineFragment);
                }
                break;
        }
        fragmentTransaction.commit();
    }


    private BroadcastReceiver screenReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if (Intent.ACTION_USER_PRESENT.equals(action)) {
                LogMds.e("cdz","收到广播了ACTION_USER_PRESENT=================================");
            }else if (Intent.ACTION_SCREEN_ON.equals(action)) {
                LogMds.e("cdz","收到广播了ACTION_SCREEN_ON=================================");
            }

            Boolean aBoolean = MMKVUtils.getBoolean(KEYS.IS_LOCK, false);
            int integer = MMKVUtils.getInteger(KEYS.LOCK_RESID, -1);
            if(integer==-1){
                return;
            }
            if (floatingLockscreen != null&&floatingLockscreen.isShow) {
                return;
            }
            if(aBoolean){
//                showWallpaperAct();
                show();
            }
        }
    };

    private void showWallpaperAct(){
        // 用户解锁屏幕，启动显示图片的界面
        Intent appIntent = new Intent(context, WallpaperActivity.class);
//        appIntent.putExtra("type",1);
        appIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(appIntent);
    }

    private FloatingLockscreen floatingLockscreen;

    public void show(){
        if (floatingLockscreen != null&&floatingLockscreen.isShow) {
            floatingLockscreen.hide();
        }
        floatingLockscreen=new FloatingLockscreen(CommUtils.getContext());
        floatingLockscreen.show();
    }
    @Override
    public int getStatusBarColor() {
        return UIUtils.getColor(com.hktf.uilib.R.color.owner_blue);
    }

    public boolean onBack() {
        DlgUtils.showDlgNew(this,null, UIUtils.getString(com.hktf.uilib.R.string.exit_app), UIUtils.getString(com.hktf.uilib.R.string.ok),
                UIUtils.getString(com.hktf.uilib.R.string.cancel), new DlgUtils.MyListener() {
                    @Override
                    public void onConfirm() {
                        exitApp();
                    }

                    @Override
                    public void onCancel() {

                    }
                });
        return true;
    }

}
